package kamikaze.service.product;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;

@ServiceConfig(path = "product/view", method = HttpMethod.GET)
public class ViewProductService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		
		ctx.getUserSession().ensureLoginAsUser();
		
		HttpServletRequest req = ctx.getRequest();
		
		final String id = req.getParameter("id");
		if (id != null && !id.isEmpty()) {

			Query q = ctx.getEntityManager().createQuery(
					"Select p from Product p where p.productId= :productId and ownerKey= :ownerKey and deleted=false");
			q.setParameter("productId", Long.valueOf(id));
			q.setParameter("ownerKey",ctx.getUserSession().asUser().getId());
			Product product = (Product) q.getSingleResult();

			req.setAttribute("product", product);
			
			return "product/view";

		} else {
			throw new ServiceException("Product ID is unknown.");
		}
	}

}
